package math2;

public class PiecewiseLinearFunctionRToR extends FunctionRnToR {

	private double[] t;
	private double[] y;

	public PiecewiseLinearFunctionRToR(double[] t, double[] y) {
		if (t.length != y.length) {
			throw new Error("length of t and y must be the same");
		}
		this.t = t;
		this.y = y;
	}

	@Override
	public double[] gradientAt(double... x) {
		if (x[0] < t[0]) {
			throw new Error("value is out of boundary domain");
		}
		for (int i = 0; i < t.length - 1; i++) {
			if (x[0] >= t[i] && x[0] < t[i + 1]) {
				return new double[] { (y[i + 1] - y[i]) / (t[i + 1] - t[i]) };
			}
		}
		if (x[0] > t[t.length - 1]) {
			throw new Error("value is out of boundary domain");
		} else {
			int i = t.length - 2;
			return new double[] { (y[i + 1] - y[i]) / (t[i + 1] - t[i]) };
		}
	}

	@Override
	public double valueAt(double... x) {
		if (x[0] < t[0]) {
			throw new Error("value is out of boundary domain");
		}
		for (int i = 0; i < t.length - 1; i++) {
			if (x[0] >= t[i] && x[0] < t[i + 1]) {
				return y[i] + (y[i + 1] - y[i]) * (x[0] - t[i]) / (t[i + 1] - t[i]);
			}
		}
		if (x[0] > t[t.length - 1]) {
			throw new Error("value is out of boundary domain");
		} else {
			return y[t.length - 1];
		}
	}

}
